/*
 * Copyright 2012-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ruisitech.bi.web;

import com.fawkes.core.base.api.ApiResponseBody;
import com.fawkes.core.base.model.CurrentUser;
import com.fawkes.core.utils.http.HttpHeaderTool;
import com.ruisitech.bi.entity.frame.User;
import com.ruisitech.bi.ext.service.SsoService;
import com.ruisitech.bi.service.frame.UserService;
import com.ruisitech.bi.util.RSBIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class SsoController {
    @Autowired
    SsoService ssoService;
    @Autowired
    private UserService userService;
    @Value("${rsbi.home}")
    private String redirectUrl;

    @GetMapping("/sso")
    public ApiResponseBody sso() {
        CurrentUser currentUser = HttpHeaderTool.getCurrentUser();
        String userName = currentUser.getUserName();
        User admin = ssoService.ssoValidate(userName);
        userService.saveUser(admin);
        String password = "123456";
        if ("admin".equals(userName)) {
            password = "rs@root@123@456";
        }
        String msg = userService.shiroLogin(userName, password);
        if ("SUC".equals(msg)) {
            //更新登陆次数及时间
            Integer userId = RSBIUtils.getLoginUserInfo().getUserId();
            userService.updateLogDateAndCnt(userId);
            return ApiResponseBody.defaultSuccess(redirectUrl);
        } else {
            return ApiResponseBody.defaultSuccess("账号或密码错误");
        }
    }
}
